
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>

int main()
{
    // 创建管道
    int pipefd[2] = {0};
    int ret = pipe(pipefd);
    if (ret < 0)
    {
        perror("pipe");
        return 1;
    }
    printf("pipefd[0]: %d, pipefd[1]: %d\n", pipefd[0], pipefd[1]);

    // fork创建子进程
    pid_t pid = fork();
    if (pid < 0) // 创建异常
    {
        perror("fork");
        return 1;
    }
    else if (pid == 0) // 子进程代码块
    {
        // 子进程(write)
        // printf("子进程写入中...\n");
        // sleep(2);
        close(pipefd[0]);
        char *msg = "hello world!";
        // write(pipefd[1],ch,strlen(msg));
        // printf("写入成功！\n");
        char outbuffer[1024];
        int cnt = 10;

        char ch = 'A';
        int size = 0;

        // while (cnt)
        while(1)
        {
            // write(pipefd[1],&ch,1);
            // size++;
            // printf("%d\n",size);

            snprintf(outbuffer, sizeof(outbuffer), "c->f# %s %d %d", msg, cnt--, getpid());
            write(pipefd[1], outbuffer, strlen(outbuffer));
            sleep(1);

            // close(pipefd[1]);
            // break;

            // if (cnt % 3 == 0)
            //     sleep(1);
        }

        // printf("write endpoint quit!\n");
        // close(pipefd[1]);

        exit(0); // 子进程结束
    }
    // 父进程(read)
    // sleep(3);
    // printf("父进程读取中...\n");
    // sleep(2);

    close(pipefd[1]);
    char inbuffer[1024];

    while (1)
    {
        // sleep(60);

        inbuffer[0]=0;

        ssize_t n = read(pipefd[0], inbuffer, sizeof(inbuffer) - 1);
        if (n > 0)
        {
            inbuffer[n] = 0;
            printf("%s\n", inbuffer);
        }
        else if (n == 0)
        {
            // printf("read pipe end of file\n");
            // break;
        }
        else
        {
            perror("read");
            break;
        }

        close(pipefd[0]);
        break;

        // printf("%s: %ld\n",inbuffer,n);
        // sleep(1);
    }

    sleep(10);

    // ssize_t n = read(pipefd[0], inbuffer, 1023);
    // inbuffer[n] = '\0';
    // printf("读取成功!\n");
    // sleep(1);
    // printf("接收到的内容为：%s\n", inbuffer);

    int status = 0;
    pid = waitpid(pid, &status, 0);
    if (pid < 0)
    {
        perror("waitpid");
        return 1;
    }
    else
    {
        printf("child quit code: %d,signal: %d\n", (status >> 8) & 0xff, status & 0x7f);
    }

    return 0;
}
